package com.dh.service.impl;

import com.dh.core.config.Constant;
import com.dh.entity.User;
import com.dh.entity.UserFlow;
import com.dh.entity.vo.UserFlowVo;
import com.dh.repository.UserFlowRepository;
import com.dh.service.UserFlowService;
import com.dh.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class UserFlowServiceImpl implements UserFlowService {

    @Autowired
    private UserFlowRepository userFlowRepository;

    @Autowired
    private UserService userService;

    public Page<UserFlowVo> page(PageRequest pageRequest) {
        return userFlowRepository.findByDeleted(Constant.NOT_DELETE, pageRequest).map(g -> {
            UserFlowVo vo = new UserFlowVo();
            BeanUtils.copyProperties(g, vo);
            vo.setUser(userService.get(g.getUserId()));
            return vo;
        });
    }

    @Override
    public UserFlow get(Long prepId) {
        return userFlowRepository.findOne(prepId);
    }


    public void delete(Long userId) {
        //        UserFlow account = userFlowRepository.findOne(userId);
        //        account.setDeleted(Constant.DELETE);
        //        userFlowRepository.save(account);
        userFlowRepository.delete(userId);
    }

    @Override
    public void create(UserFlow flow) {
        User user = userService.get(flow.getUserId());
        user.setDeleted(Constant.HASFLOW);
        userService.update(user);
        userFlowRepository.save(flow);
    }

    @Override
    public void update(UserFlow flow) {
        userFlowRepository.save(flow);
    }

    @Override
    public UserFlow findByNoAndDeleted(String no, byte deleted) {
        return userFlowRepository.findByNoAndDeleted(no, deleted);
    }

}
